/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.zrb.backend.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.consts.GlobalConst;
import com.hanhai.common.util.CookieWrapper;
import com.hanhai.zrb.backend.admin.model.BackendUser;

/**
 * 后端用的登录工具。
 */
public class BackendLoginUtil {
	public static Logger logger = Logger.getLogger(BackendLoginUtil.class);
	public static final ThreadLocal<BackendUser> currentUser = new ThreadLocal<BackendUser>();

	public static String getCookieValue(HttpServletRequest req,
			HttpServletResponse res, String cookieName) {
		String value = CookieWrapper.getCookieValue(req, cookieName);
		return value;
	}

	public static void setCurrentUser(BackendUser user) {
		currentUser.set(user);

	}

	public static BackendUser getCurrentUser() {
		return currentUser.get();
	}

	public static void initCurrentUser(HttpServletRequest req, Cache loginCache) {
		String key = CookieWrapper.getCookieValue(req,
				GlobalConst.BackendCookieName);
		if (StringUtils.isNotBlank(key)) {
			Object user = loginCache.getValue(key);
			if (user != null) {
				if (user instanceof BackendUser) {
					BackendUser backendUser = (BackendUser) user;
					setCurrentUser(backendUser);
					Boolean autoLogin = backendUser.getAutoLogin();
					if (!autoLogin) {
						int timeout = BackendLoginUtil.timeout(autoLogin);
						loginCache.add(key, user, timeout);
					}
				} else {
					logger.error("backend,user is not backendUser");
				}
			}
		}
	}

	public static int timeout(boolean autoLogin) {
		int timeout = GlobalConst.SESSION_TIMEOUT_SECONDS_BACKEND;
		if (autoLogin) {
			timeout = GlobalConst.KEEP_LOGIN_TIME_BACKEND;
		}
		return timeout;
	}

	public static int expire(boolean autoLogin) {
		int expire = GlobalConst.BROWSER_SESSION_MAX_AGE;
		if (autoLogin) {
			expire = GlobalConst.KEEP_LOGIN_TIME_BACKEND;
		}
		return expire;
	}

}
